package jdbc;
import org.junit.Test;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * jdbc完成事务处理
 * Created by kevin on 2020/3/25.
 */
public class Demo4 {
    public void zhuanzhang(String from,String to,double money){
        Connection connection = null;
        try {
            //Connection 同一事务中的所有操作,都在使用同一个Connection对象
            connection = JdbcUtils.getConnection();
            //开启事务
            connection.setAutoCommit(false);
            AccountDao accountDao = new AccountDao();
            accountDao.updateBalance(connection,from,-10000);
            if(true){
                throw new RuntimeException("失败了");
            }
            accountDao.updateBalance(connection,to,+10000);
            //提交事务
            connection.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                //回滚事务
                connection.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        } finally {
            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void fun1(){
        zhuanzhang("ls","zs",10000);
    }
}
